﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using BP.OA;
using BP.Web;
using BP.OA.Meeting;
using BP.WF;
using BP.WF.Template;

namespace CCOA.App.Meeting
{
    public partial class Order : System.Web.UI.Page
    {
        public string FK_RoomNo
        {
            get
            {
                return Request.QueryString["id"];
            }
        }
        public Rooms rooms = new Rooms();
        public RoomOrding ording = new RoomOrding();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
            }
            else
            {
                SaveOrUpdate();
            }
        }

        /// <summary>
        /// 实体数据代入
        /// </summary>
        void BindData()
        {
            rooms.RetrieveByAttr(RoomAttr.RoomSta, "0");
            string oid = Request.QueryString["OID"];
            string id = Request.QueryString["id"];
            if (!string.IsNullOrEmpty(id))
            {
                ording.Fk_Room = id;
            }
            if (!string.IsNullOrEmpty(oid))
            {
                RoomOrdings ordings = new RoomOrdings();
                ordings.Retrieve("OID", oid);
                if (ordings.Count > 0)
                {
                    ording = ordings[0] as RoomOrding;
                }
            }
        }

        /// <summary>
        /// 新建或更新
        /// </summary>
        private void SaveOrUpdate()
        {
            RoomOrding ording = new RoomOrding();
            ording = BP.OA.UI.PageCommon.GetEntity(this, ording) as RoomOrding;
            ording.OID = Convert.ToInt32(Request.Form["OID"]);
            if (ording.OID == 0)//插入
            {
                Insert(ording);
            }
            else//更新
            {
                Update(ording);
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="ording"></param>
        protected void Insert(RoomOrding ording)
        {
            ording.State = "0";
            string dtStart = Convert.ToDateTime(ording.DateFrom).ToString();
            string dtEnd = Convert.ToDateTime(ording.DateTo).ToString();

            bool IsCanOrder = GetSql(ording.Fk_Room, ording.OID, dtStart, dtEnd);

            if (IsCanOrder == false)
            {
                Common.Alert("该时间段已经有预定！", this);
            }
            else
            {
                //查看接受人员/岗位/部门
                //记录编号 和 名称
                GetEmpStationDept(ording);

                if (ording.Insert() > 0)
                {
                    //发短消息
                    string toEmps = GetSMSToEmps(ording);
                    // BP.OA.ShortMsg.Send_Notice(toEmps, "会议通知", "", ording.OID.ToString(), false);

                    // PushMsg pm = new PushMsg();
                    //pm.DoSendMessage(null,ording,"",null, null, toEmps);                 
                    Refresh("alert('预定成功！');");
                }
                else
                    Common.Alert("预定失败！", this);
            }
        }



        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="ording"></param>
        protected void Update(RoomOrding ording)
        {
            string dtStart = Convert.ToDateTime(ording.DateFrom).ToString();
            string dtEnd = Convert.ToDateTime(ording.DateTo).ToString();
            bool IsCanOrder = GetSql(ording.Fk_Room, ording.OID, dtStart, dtEnd);
            if (IsCanOrder == false)
            {
                Common.Alert("该时间段已经有预定！", this);
            }
            else
            {
                //查看接受人员/岗位/部门
                GetEmpStationDept(ording);

                if (ording.Update() > 0)
                {
                    //发短消息
                    string userNos = String.Join(",", ording.ToEmps);
                    BP.OA.ShortMsg.Send_Notice(userNos, "会议更改通知", "", ording.OID.ToString(), false);
                    Refresh("alert('更新成功，已通知参与人员！');");
                }
                else
                    Common.Alert("更新失败！", this);

            }
        }
        /// <summary>
        /// 判断会议室是否可以预定
        /// </summary>
        /// <param name="RoomNo">会议室编号</param>
        /// <param name="OrderOID">预定编号</param>
        /// <param name="strStart">预定开始时间</param>
        /// <param name="strEnd">预定结束时间</param>
        /// <returns></returns>
        bool GetSql(string RoomNo, int OrderOID, string strStart, string strEnd)
        {
            string strSql = "select * from OA_RoomOrding where Fk_Room='{0}'";
            DataTable table = BP.DA.DBAccess.RunSQLReturnTable(string.Format(strSql, RoomNo));
            //排除已结束和已取消的和正在修改的预定。
            DataRow[] drs = table.Select("State<>2 and State<>3 and OID<>" + OrderOID.ToString());
            //用户选择的开始时间和结束时间
            DateTime dtStart = Convert.ToDateTime(strStart);
            DateTime dtEnd = Convert.ToDateTime(strEnd);
            foreach (DataRow dr in drs)
            {
                DateTime dtFrom = Convert.ToDateTime(dr["DateFrom"]);
                DateTime dtTo = Convert.ToDateTime(dr["DateTo"]);
                //若选择的开始时间小于查询到的开始时间，那么选择的结束时间也必须小于查询到的开始时间
                if (dtStart < dtFrom)
                {
                    if (dtEnd > dtFrom)
                    {
                        return false;
                    }
                }
                //若选择的开始时间大于查询到的开始时间则选择的开始时间也必须大于查询到的结束时间。
                else
                {
                    if (dtTo > dtStart)
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 获取 实体数据
        /// </summary>
        public void GetEmpStationDept(RoomOrding ording)
        {
            ording.ToEmps = this.txt_ToEmps.Value;
            ording.ToEmpNames = Request.Form["txt_ToEmpNames2"].ToString();
            if (ording.ToEmpNames == "")
            {
                ording.ToEmps = "all";
                ording.ToEmpNames = "所有人员";
            }
            ording.ToStations = this.txt_ToStations.Value;
            ording.ToStationNames = Request.Form["txt_ToStationNames"].ToString();
            if (ording.ToStationNames == "")
            {
                ording.ToStations = "all";
                ording.ToStationNames = "所有岗位";
            }
            ording.ToDepts = this.txt_ToDepts.Value;
            ording.ToDeptNames = Request.Form["txt_ToDeptNames"].ToString();
            if (ording.ToDeptNames == "")
            {
                ording.ToDepts = "all";
                ording.ToDeptNames = "所有部门";
            }
        }

        /// <summary>
        /// 获取 需要发送通知的人员列表
        /// </summary>
        /// <returns></returns>
        public string GetSMSToEmps(RoomOrding ording)
        {
            string strEmps = "";
            string strsql = "";
            DataTable dtemps = null;
            //判断部门
            if (ording.ToEmps == "all")
            {
                dtemps = BP.DA.DBAccess.RunSQLReturnTable("SELECT NO FROM PORT_EMP");
                foreach (DataRow dr in dtemps.Rows)
                {
                    strEmps += dr["No"].ToString() + ",";
                }
                strEmps = strEmps.Substring(0, strEmps.Length - 1);
            }
            else
            {
                //先排除固定人员列表
                string oldemps = "'" + ording.ToEmps.ToString().Replace(",", "','") + "'";
                strsql = "SELECT  FK_EMP  FROM PORT_DEPTEMPSTATION WHERE FK_EMP NOT IN (" + oldemps + ")";
                if (ording.ToDepts != "all")
                    strsql += " AND  FK_DEPT IN (" + ording.ToDepts + ")";
                if (ording.ToStations != "all")
                    strsql += " AND FK_STATION IN (" + ording.ToStations + ")";
                dtemps = BP.DA.DBAccess.RunSQLReturnTable(strsql);
                foreach (DataRow dr in dtemps.Rows)
                {
                    strEmps += dr["FK_EMP"].ToString() + ",";
                }
                strEmps += ording.ToEmps;
            }
            return strEmps;
        }

        public void Refresh(string strJs)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "info", strJs + "RefreshParent();", true);
        }

        public string GetResourceName(object obj)
        {
            return MyHelper.GetResName(obj);
        }
    }
}